import axios from 'axios'

const service = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(config => {
  // // 排除登录和注册接口
  const allowUrls = ['/users/login', '/users/register']
  if (allowUrls.includes(config.url)) return config
  // if (config.responseType === 'blob') {
  //   console.log(localStorage)
  //   config.transformResponse = [data => data] // 禁用JSON转换
  //   config.headers['Content-Type'] = 'application/octet-stream'
  //   config.headers['Cache-Control'] = 'no-cache, no-store'
  //   config.headers.Pragma = 'no-cache'
  // }
  const token = localStorage.getItem('token')

  const userId = localStorage.getItem('userId')
// 处理JSON数据校验
  // 在axios请求拦截器中添加

  if (config.data) {
    // 餐厅创建校验
    if (config.url === '/restaurants' && config.method === 'post') {
      if (!config.data.name?.trim()) {
        return Promise.reject({ message: '餐厅名称不能为空' })
      }
    }
    // 部门创建校验
    if (config.url === '/departments' && config.method === 'post') {
      if (!config.data.name?.trim()) {
        return Promise.reject({ message: '部门名称不能为空' })
      }
      if (!config.data.restaurantId) {
        return Promise.reject({ message: '必须选择关联餐厅' })
      }
    }
  }
  // 验证逻辑
  if (!token || !userId) {
    if (window.location.pathname !== '/login') {
      localStorage.clear()
      window.location.href = `/login?from=${encodeURIComponent(window.location.pathname)}`
    }
    return Promise.reject('缺少认证信息')
  }

  // 添加请求头
  config.headers['X-Debug-User'] = userId
  config.headers.Authorization = `${token}`

  // 处理文件下载请求
  if (config.responseType === 'blob') {
    config.headers['Content-Type'] = 'application/octet-stream'
  }

  return config
})

// 响应拦截器
service.interceptors.response.use(
    response => {
      // 处理文件下载响应
      if (response.config.responseType === 'blob') {
        return {
          success: true,
          code: response.status,
          data: response.data,
          headers: response.headers
        }
      }

      // 统一响应格式
      return {
        success: true,
        code: response.status,
        data: response.data?.data || response.data,
        total: response.data?.total,    // 分页总数
        headers: response.headers
      }
    },
    error => {
      const errorInfo = {
        code: error.response?.status || 500,
        message: error.response?.data?.message || '网络请求失败',
        details: error.config
      }

      console.error('请求异常:', errorInfo)

      // 处理401错误
      if (errorInfo.code === 401) {
        localStorage.clear()
        window.location.reload()
      }

      return Promise.reject(errorInfo)
    }
)

// 用户模块
export const userRegister = (data) => service.post('/users/register', data)
export const userLogin = (data) => service.post('/users/login', data)
export const getUserInfo = () => service.get('/users')

// 餐厅模块
export const getRestaurants = (params) => service.get('/restaurants', { params })
export const createRestaurant = (data) => service.post('/restaurants', data)
export const deleteRestaurant = (id) => service.delete(`/restaurants/${id}`)

// 菜品模块
export const getDishesByPage = (params) => service.get('/dishes', {
  params: {
    page: params.page,
    size: params.size,
    fields: params.fields,
    selectedDate: params.selectedDate,  // 新增日期过滤
    restaurantId: params.restaurantId,
    departmentId: params.departmentId
  }
})
export const getDishesByRestaurant = (restaurantId, departmentId, date) =>
    service.get('/dishes/by-restaurant', {
      params: {
        restaurantId: Number(restaurantId),
        departmentId: departmentId ? Number(departmentId) : undefined, // 处理undefined情况
        selectedDate: date || undefined,
        page: 1,
        size: 1000
      }
    })
export const updateDish = (id, data) => service.put(`/dishes/${id}`, {
  ...data,
  categorizedAt: new Date().toISOString() // 更新分类时间
})
export const deleteDish = (id) => service.delete(`/dishes/${id}`)
export const getAllDishes = () => service.get('/dishes/getall')
export const addDish = (data) => service.post('/dishes/add', {
  ...data,
  restaurantId: Number(data.restaurantId),
  departmentId: Number(data.departmentId)
})
// 新增功能接口
export const batchCategorize = (data) => service.put('/dishes/batch-categorize', data)

export const getCategories = () => service.get('/dishes/categories')
// 在部门模块导出部分补充删除接口
export const deleteDepartment = (id) => service.delete(`/departments/${id}`)

export const getAllDepartments = (params = {}) => {
  return service.get('/departments', {
    params: {
      restaurantId: params.restaurantId ? Number(params.restaurantId) : undefined
    }
  })
}
export const addDepartment = (data) => service.post('/departments', data)

// 确保已存在以下导出
export const updateDepartment = (id, data) => service.put(`/departments/${id}`, data)
export const updateRestaurant = (id, data) => service.put(`/restaurants/${id}`, data)
export const exportAllDishes = () => service.get('/dishes/export-all', {
  responseType: 'blob'
});
// 前端api/index.js
export const exportSelectedDishes = (ids) => service.get('/dishes/export-selected', {
  params: {
    ids: ids.join(',') // 将数组转换为逗号分隔字符串
  },
  responseType: 'blob',
  headers: {
    'Cache-Control': 'no-cache, no-store'
  }
})
export const exportDishes = (category) => service.get('/dishes/export', {
  params: { category },
  responseType: 'blob'  // 文件下载必须配置
})
// 按照购物清单格式按日期导出
export const exportDishesByDate = (date) => service.get('/dishes/export-by-date', {
  params: { date },
  responseType: 'blob'
})